'use client';

import { getUser, login } from 'src/actions/user';
import { startTransition, useActionState, useCallback } from 'react';
import Link from 'next/link';
import { Alert } from 'src/components/Alert';
import { useRouter, useSearchParams } from 'next/navigation';
import { LockClosedIcon, UserIcon } from '@heroicons/react/24/outline';
import { useMount } from 'ahooks';
import toast from 'react-hot-toast';

export default function Login() {
  const [state, action, pending] = useActionState(login, undefined);

  const searchParams = useSearchParams();

  const router = useRouter();

  const handleSubmit = useCallback(
    (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault();
      const formData = new FormData(event.currentTarget);
      startTransition(async () => {
        await action(formData);
      });
    },
    [action]
  );

  const handleRedirect = useCallback(() => {
    let redirectUrl = '/';
    const redirect = searchParams.get('redirect');
    if (redirect) redirectUrl = redirect;
    router.replace(redirectUrl);
  }, [router, searchParams]);

  useMount(() => {
    getUser().then((user) => {
      if (user) {
        toast.success('您已登录，无需重复登录，跳转到首页');
        router.replace('/');
      }
    });
  });

  return (
    <div className="flex items-center justify-center min-h-screen bg-gradient-to-b from-gray-100 to-purple-200 dark:from-neutral-800 dark:to-purple-950 p-4">
      {state?.status === 'success' && (
        <Alert
          key={state.actionId}
          duration={2000}
          type="success"
          message="登录成功，欢迎回来！"
          onClose={handleRedirect}
        />
      )}
      {state?.status === 'error' && (
        <Alert key={state.actionId} type="error" message={state.errors?.message ?? '登录失败'} />
      )}
      <div className="w-full max-w-md p-8 space-y-6 bg-white dark:bg-neutral-950 rounded-2xl shadow-lg">
        <div className="text-center">
          <h1 className="text-3xl font-bold">用户登录 </h1>
          <p className="mt-2 text-sm text-gray-600 dark:text-neutral-400">
            🎉欢迎来到星恒云图，登录您的账户
          </p>
        </div>

        <form onSubmit={handleSubmit} className="mt-8">
          <fieldset className="fieldset text-sm">
            <label htmlFor="email" className="label">
              账号
            </label>
            <label className="input input-lg w-full pr-0">
              <UserIcon className="size-6 opacity-75" />
              <input
                id="email"
                name="email"
                type="email"
                required
                autoComplete="email"
                placeholder="请输入用户名或邮箱"
              />
            </label>
            <p className="flex items-center h-6 text-xs text-error">{state?.errors?.form?.email}</p>

            <label htmlFor="password" className="label">
              密码
            </label>
            <label className="input input-lg w-full pr-0">
              <LockClosedIcon className="size-6 opacity-75" />
              <input
                id="password"
                name="password"
                type="password"
                required
                placeholder="请输入密码"
                autoComplete="current-password"
              />
            </label>
            <p className="flex items-center h-6 text-xs text-error">
              {state?.errors?.form?.password}
            </p>

            <div className="text-right mb-3 -mt-2">
              <Link href="/forget" className="text-blue-600 hover:text-blue-800 font-medium">
                忘记密码？
              </Link>
            </div>

            <button
              disabled={pending}
              type="submit"
              className="w-full py-3 px-4 text-lg bg-gradient-to-r from-purple-500 to-purple-600 text-white font-medium rounded-lg transition-all duration-200 hover:from-purple-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 disabled:opacity-70"
            >
              {pending && <span className="loading loading-spinner mr-1" />}
              {pending ? '登录中...' : '登录'}
            </button>
          </fieldset>
        </form>

        <div className="text-center text-sm text-gray-600 dark:text-neutral-400">
          <p>
            还没有账号？
            <Link href="/signup" className="text-blue-600 hover:text-blue-800 font-medium">
              立即注册
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
